<script setup lang="ts">
import { ref, onBeforeMount, watchEffect } from 'vue';
import { quasarFormStyle, quasarTableStyle } from '@/setting.ts';
import type {
  Category,
  SkuInfo,
  AttrInfo,
  AttrValue,
  SpuSaleAttr,
  SpuImage,
  SkuAttrValue,
  SkuSaleAttrValue,
  SpuSaleAttrValue,
  SkuImage
} from '@/api/product/type.ts';
import {
  reqGetSpuSaleAttrList,
  reqGetSpuImageList,
  reqSaveSkuInfo
} from '@/api/product/spu.ts';
import { reqGetAttrInfoList } from '@/api//product/attr.ts';
import { useQuasar } from 'quasar';
import type { QTableColumn } from 'quasar';

const { notify } = useQuasar();
//
const props = defineProps<{
  spuId: number;
  category: Category;
}>();
const $emit = defineEmits<{
  hideSkuForm: [flag?: string];
}>();
// skuForm
const skuForm = ref<SkuInfo>({
  spuId: props.spuId,
  category3Id: props.category.category3Id,
  skuName: '',
  skuDesc: '',
  price: null,
  weight: '',
  skuImageList: [] as SkuImage[],
  skuAttrValueList: [] as SkuAttrValue[],
  skuSaleAttrValueList: [] as SkuSaleAttrValue[]
});
// 获取平台属性列表
const platformAttrList = ref<AttrInfo[]>([]);
async function getPlatformAttrList() {
  try {
    const result = await reqGetAttrInfoList(props.category);
    if (result.code === 200) {
      platformAttrList.value = result.data;
    } else {
      throw new Error('平台属性列表获取失败');
    }
  } catch (error: any) {
    notify({
      type: 'negative',
      message: error.message,
      position: 'top'
    });
  }
}
// SkuAttrValue
// 添加一个attrValueList属性，也最后提交数据时删除该属性
interface SelectSkuAttrValue extends SkuAttrValue {
  attrValueList?: AttrValue[];
}
const skuAttrValueList = ref<SelectSkuAttrValue[]>([]);
watchEffect(() => {
  skuAttrValueList.value = platformAttrList.value.map(item => {
    return {
      valueId: null,
      attrId: item.id!,
      attrName: item.attrName,
      attrValueList: item.attrValueList
    };
  });
});
// 获取销售属性列表
const saleAttrList = ref<SpuSaleAttr[]>([]);
async function getSaleAttrList() {
  try {
    const result = await reqGetSpuSaleAttrList(props.spuId);
    if (result.code === 200) {
      saleAttrList.value = result.data;
    } else {
      throw new Error('销售属性列表获取失败');
    }
  } catch (error: any) {
    notify({
      type: 'negative',
      message: error.message,
      position: 'top'
    });
  }
}
// 销售属性选择列表
interface SelectSkuSaleAttrValue extends SkuSaleAttrValue {
  spuSaleAttrValueList?: SpuSaleAttrValue[];
}
const skuSaleAttrList = ref<SelectSkuSaleAttrValue[]>([]);
watchEffect(() => {
  skuSaleAttrList.value = saleAttrList.value.map(item => {
    return {
      saleAttrId: item.id!,
      saleAttrName: item.saleAttrName,
      saleAttrValueId: null,
      spuSaleAttrValueList: item.spuSaleAttrValueList
    };
  });
});
// 获取spu图片列表
const spuImageList = ref<SpuImage[]>([]);
async function getSpuImageList() {
  try {
    const result = await reqGetSpuImageList(props.spuId);
    if (result.code === 200) {
      spuImageList.value = result.data;
    } else {
      throw new Error('spu图片列表获取失败');
    }
  } catch (error: any) {
    notify({
      type: 'negative',
      message: error.message,
      position: 'top'
    });
  }
}
// Sku图片
const skuImageList = ref<SkuImage[]>([]);
watchEffect(() => {
  skuImageList.value = spuImageList.value.map(item => {
    return {
      imgName: item.imgName,
      imgUrl: item.imgUrl,
      spuImgId: item.id!,
      isDefault: '0'
    };
  });
});
// 表格
// 列
const skuImageColumns: QTableColumn[] = [
  { name: 'imgUrl', label: '图片', field: '', align: 'left' },
  { name: 'imgName', label: '名称', field: 'imgName', align: 'left' },
  { name: 'control', label: '操作', field: '', align: 'left' }
];
// 设置默认图片
function setDefaultImg(row: SkuImage) {
  //
  skuForm.value.skuImageList.forEach(item => {
    item.isDefault = '0';
  });
  const img = skuForm.value.skuImageList.findIndex(
    item => item.spuImgId === row.spuImgId
  );
  if (img >= 0) {
    skuForm.value.skuImageList[img].isDefault = '1';
  } else {
    row.isDefault = '1';
    skuForm.value.skuImageList.unshift(row);
  }
  skuForm.value.skuDefaultImg = row.imgUrl;
}
// 提交表单
async function onSubmit() {
  // 整理数据
  // 整理平台属性列表
  skuForm.value.skuAttrValueList = skuAttrValueList.value
    .map(item => {
      const attr = { ...item };
      delete attr.attrValueList;
      return attr;
    })
    .filter(item => item.valueId !== null);
  // 整理销售属性列表
  skuForm.value.skuSaleAttrValueList = skuSaleAttrList.value
    .map(item => {
      const saleAttr = { ...item };
      delete saleAttr.spuSaleAttrValueList;
      return saleAttr;
    })
    .filter(item => item.saleAttrValueId !== null);
  try {
    const result = await reqSaveSkuInfo(skuForm.value);
    if (result.code === 200) {
      notify({
        type: 'positive',
        message: '提交SKU数据成功',
        position: 'top'
      });
      $emit('hideSkuForm', 'ok');
    } else {
      throw new Error('提交SKU数据失败');
    }
  } catch (error: any) {
    notify({
      type: 'negative',
      message: error.message,
      position: 'top'
    });
  }
}
onBeforeMount(() => {
  getPlatformAttrList();
  getSaleAttrList();
  getSpuImageList();
});
</script>

<template>
  <q-card class="q-mt-md">
    <q-card-section>
      <q-input
        v-bind="quasarFormStyle"
        dense
        label="SKU名称"
        v-model="skuForm.skuName"
      ></q-input>
      <q-input
        v-bind="quasarFormStyle"
        dense
        class="q-my-md"
        label="价格（元）"
        v-model="skuForm.price"
        type="number"
      ></q-input>
      <q-input
        v-bind="quasarFormStyle"
        dense
        label="重量（g）"
        v-model="skuForm.weight"
      ></q-input>
      <q-input
        v-bind="quasarFormStyle"
        label="SKU描述"
        class="q-mt-md"
        type="textarea"
        input-style="height: 60px;"
        dense
        v-model="skuForm.skuDesc"
      ></q-input>
      <q-field label="平台属性" dense readonly borderless class="q-my-xs" />
      <div class="row flex-wrap q-gutter-sm">
        <q-select
          v-for="attr in skuAttrValueList"
          :key="attr.attrId"
          :label="attr.attrName"
          v-bind="quasarFormStyle"
          style="width: 180px"
          v-model="attr.valueId"
          :options="attr.attrValueList"
          option-value="id"
          emit-value
          option-label="valueName"
          map-options
          dense
          options-dense
        />
      </div>
      <q-field label="销售属性" dense readonly borderless class="q-my-xs" />
      <div class="row flex-wrap q-gutter-sm">
        <q-select
          v-for="attr in skuSaleAttrList"
          :key="attr.saleAttrId"
          :label="attr.saleAttrName"
          v-bind="quasarFormStyle"
          style="width: 180px"
          v-model="attr.saleAttrValueId"
          :options="attr.spuSaleAttrValueList"
          option-value="id"
          emit-value
          option-label="saleAttrValueName"
          map-options
          dense
          options-dense
        />
      </div>
      <q-field label="SKU图片" dense readonly borderless class="q-my-xs" />
      <q-table
        :separator="quasarTableStyle"
        :rows="skuImageList"
        :columns="skuImageColumns"
        hide-pagination
        row-key="spuImgId"
        :rows-per-page-options="[0]"
        selection="multiple"
        v-model:selected="skuForm.skuImageList"
        hide-bottom
      >
        <template #body-cell-imgUrl="{ row }">
          <q-td>
            <q-img :src="row.imgUrl"></q-img>
          </q-td>
        </template>
        <template #body-cell-control="{ row }">
          <q-td>
            <q-btn
              label="设置默认"
              size="xs"
              color="primary"
              @click="setDefaultImg(row)"
              v-if="row.isDefault === '0'"
            ></q-btn>
            <div v-else>默认图片</div>
          </q-td>
        </template>
      </q-table>
      <div class="row q-gutter-sm q-mt-md">
        <q-btn
          v-bind="quasarFormStyle"
          color="primary"
          label="保存"
          @click="onSubmit"
        ></q-btn>
        <q-btn
          v-bind="quasarFormStyle"
          color="primary"
          flat
          label="取消"
          @click="$emit('hideSkuForm')"
        ></q-btn>
      </div>
    </q-card-section>
  </q-card>
</template>

<style scoped>
/* 	code... */
</style>
